<?php

namespace app\admin\controller;
use app\common\controller\Backend;
use think\Db;
use fast\Random;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Request;

use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Command extends Backend
{
    /**
     * Dispatch
     * @var \app\admin\model\Dispatch
     */
    protected $noNeedLogin = ['test'];
    protected $model = null;
    protected $fiveindustryArr = [];
    protected $streetArr = [];
    protected $industryCategoryArr = [];
    protected $tablename = 'command';
    protected $year;
    protected $chargedep_data = null;
    protected $pre = '';
    protected $project_socialized = [];
    public function _initialize()
    {
        parent::_initialize();

        $this->model = new \app\admin\model\Command;
        $this->command_model = new \app\admin\model\CommandType;

        $this -> year = $this -> request -> get('year',date('Y'));
        $this->projectmodel = new \app\admin\model\Project();


        $groupIds = $this->auth->getGroupIds();
        $this->assignconfig('isSuperAdmin',$this->auth->isSuperAdmin());
        $this->assign('isSuperAdmin',$this->auth->isSuperAdmin());
        $this->assignconfig('uid',$this->auth->id);
        $this->chargedep_data = $this->auth->getChargedep();

        if($this->chargedep_data)
        {
            $chargedep_id = $this->chargedep_data->chargedep_id;
            $this->assignconfig('isbinddep',1);
        }
        else
        {
            $chargedep_id = 0;
            $this->assignconfig('isbinddep',0);
        }

        $this->assignconfig('chargedep_id',$chargedep_id);
        if($this->auth->isSuperAdmin())
            $this->pre = '';
        else
            $this->pre = 'tmp_';
        $this->assign('pre',$this->pre);
        $this->assignconfig('pre',$this->pre);

        $this->progress_model = new \app\admin\model\Progress;
        $this->chargedep_model = new \app\admin\model\Chargedep;

        // 项目状态
        $progress_list = $this->progress_model->select();
        $this->assign('progress_list',$progress_list);

        // 负责部门
        $chargedep_list = $this->chargedep_model->select();
        $this->assign('chargedep_list',$chargedep_list);

        // $command_list = $this->command_model->order('id')->select();
        // $this->assign('command_list',$command_list);

        $this -> assign('command_list',getSelectList('command_type'));

    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    // 基础信息维护，专题调度项目类型，每添加一个，这个获取
    public function type($typeid = null)
    {
        // $this->whereExtend['command_typeid'] = $typeid;
        $this->whereExtend[] = ['exp',Db::raw("FIND_IN_SET($typeid,command_typeid)")];

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where($this->whereExtend)
                ->count();
            $list = $this->model
                ->where($where)
                ->where($this->whereExtend)
                ->order($this->sortExtend)
                ->limit($offset, $limit)
                ->select();
            // echo $this->model->getLastSql();exit();
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $this->assign('typeid',$typeid);
        $this->assignconfig('typeid',$typeid);
        return $this->view->fetch();
    }

    public function type_add($typeid = null)
    {
        return $this -> command_add($typeid);
    }

    protected function command_add($addId = NULL){
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $insert_data['name'] = $params['name'];

                $insert_data['investment_total'] = $params['investment_total'];
                $insert_data['carrier_area'] = $params['carrier_area'];
                $insert_data['summary'] = $params['summary'];
                $insert_data['status_name'] = $params['status_name'];
                $insert_data['exist_question'] = $params['exist_question'];

                // if($addId){
                //     $info = $this->command_model->get($addId);
                //     if($info)
                //         $insert_data['command_type'] = $info['name'];
                //     $insert_data['command_typeid'] = $addId;
                // }

                // 项目类型
                $command_typeid = '';
                $command_type = '';
                if (isset($params['command_typeid'])) {
                    foreach($params['command_typeid'] as $key => $value)
                    {
                        $command_typeid .= $value.",";
                        $info = $this->command_model->get($value);
                        if($info)
                            $command_type .= $info['name'].',';
                    }
                    $command_typeid = substr($command_typeid,0,strlen($command_typeid)-1);
                    $command_type = substr($command_type,0,strlen($command_type)-1);

                }
                $insert_data['command_typeid'] = $command_typeid;
                $insert_data['command_type'] = $command_type;

                $project_row = $this->projectmodel->where(['name'=>$params['name']])->find();
                if($project_row)
                    $insert_data['project_pno'] = $project_row['pno'];

                if(isset($params['access_time']))
                {
                    $insert_data['access_time'] = strtotime($params['access_time']);
                    $insert_data['access_time_desc'] = $params['access_time'];
                }
                if(isset($params['sign_time']))
                {
                    $insert_data['sign_time'] = strtotime($params['sign_time']);
                    $insert_data['sign_time_desc'] = $params['sign_time'];
                }
                if(isset($params['framework_agreement_time']))
                {
                    $insert_data['framework_agreement_time'] = strtotime($params['framework_agreement_time']);
                    $insert_data['framework_agreement_time_desc'] = $params['framework_agreement_time'];
                }
                if(isset($params['invesment_agreement_time']))
                {
                    $insert_data['invesment_agreement_time'] = strtotime($params['invesment_agreement_time']);
                    $insert_data['invesment_agreement_time_desc'] = $params['invesment_agreement_time'];
                }
                if(isset($params['register_time']))
                {
                    $insert_data['register_time'] = strtotime($params['register_time']);
                    $insert_data['register_time_desc'] = $params['register_time'];
                }
                if(isset($params['land_time']))
                {
                    $insert_data['land_time'] = strtotime($params['land_time']);
                    $insert_data['land_time_desc'] = $params['land_time'];
                }
                if(isset($params['start_construction_time']))
                {
                    $insert_data['start_construction_time'] = strtotime($params['start_construction_time']);
                    $insert_data['start_construction_time_desc'] = $params['start_construction_time'];
                }

                if(isset($params['operate_time']))
                {
                    $insert_data['operate_time'] = strtotime($params['operate_time']);
                    $insert_data['operate_time_desc'] = $params['operate_time'];
                }

                if(isset($params['remove_time']))
                {
                    $insert_data['remove_time'] = strtotime($params['remove_time']);
                    $insert_data['remove_time_desc'] = $params['remove_time'];
                }

                if (isset($params['settle_street_ids'])) {
                    $row_info = $this->chargedep_model->get($params['settle_street_ids']);
                    $accompany_name = $row_info->name;
                    $insert_data['settle_street_ids'] = $params['settle_street_ids'];
                    $insert_data['settle_street_names'] = $accompany_name;
                }

                if (isset($params['chargedep_ids'])) {
                    $row_info = $this->chargedep_model->get($params['chargedep_ids']);
                    $accompany_name = $row_info->name;
                    $insert_data['chargedep_ids'] = $params['chargedep_ids'];
                    $insert_data['chargedep_names'] = $accompany_name;
                }

                if (isset($params['status_id'])) {
                    $row_info = $this->progress_model->get($params['status_id']);
                    $accompany_name = $row_info->name;
                    $insert_data['status_id'] = $params['status_id'];
                    $insert_data['status'] = $accompany_name;
                }

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($insert_data);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assign('addId',$addId);
        return $this->view->fetch('add');
    }


    public function edit($ids = NULL) {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $project_params = [];

                $updateData = [];
                $updateDataProject = [];

                if($row['project_pno'])
                {
                    $project_row = $this->projectmodel->where(['name'=>$params['name']])->find();
                    if(isset($project_row))
                        $updateData['project_pno'] = $project_row['pno'];
                }

                // 项目类型
                $command_typeid = '';
                $command_type = '';
                if (isset($params['command_typeid'])) {
                    foreach($params['command_typeid'] as $key => $value)
                    {
                        $command_typeid .= $value.",";
                        $info = $this->command_model->get($value);
                        if($info)
                            $command_type .= $info['name'].',';
                    }
                    $command_typeid = substr($command_typeid,0,strlen($command_typeid)-1);
                    $command_type = substr($command_type,0,strlen($command_type)-1);

                }
                $updateData['command_typeid'] = $command_typeid;
                $updateData['command_type'] = $command_type;


                $updateData['name']= $params['name'];
                $updateDataProject['name'] = $params['name'];

                if(isset($params['access_time']))
                {
                    $updateData['access_time'] = strtotime($params['access_time']);
                    $updateData['access_time_desc'] = $params['access_time'];

                    $updateDataProject['access_time'] = strtotime($params['access_time']);
                    $updateDataProject['access_time_desc'] = $params['access_time'];
                }
                if(isset($params['sign_time']))
                {
                    $updateData['sign_time'] = strtotime($params['sign_time']);
                    $updateData['sign_time_desc'] = $params['sign_time'];

                    $updateDataProject['sign_time'] = strtotime($params['sign_time']);
                    $updateDataProject['sign_time_desc'] = $params['sign_time'];
                }
                if(isset($params['framework_agreement_time']))
                {
                    $updateData['framework_agreement_time'] = strtotime($params['framework_agreement_time']);
                    $updateData['framework_agreement_time_desc'] = $params['framework_agreement_time'];

                    $updateDataProject['framework_agreement_time'] = strtotime($params['framework_agreement_time']);
                    $updateDataProject['framework_agreement_time_desc'] = $params['framework_agreement_time'];
                }
                if(isset($params['invesment_agreement_time']))
                {
                    $updateData['invesment_agreement_time'] = strtotime($params['invesment_agreement_time']);
                    $updateData['invesment_agreement_time_desc'] = $params['invesment_agreement_time'];

                    $updateDataProject['invesment_agreement_time'] = strtotime($params['invesment_agreement_time']);
                    $updateDataProject['invesment_agreement_time_desc'] = $params['invesment_agreement_time'];
                }
                if(isset($params['register_time']))
                {
                    $updateData['register_time'] = strtotime($params['register_time']);
                    $updateData['register_time_desc'] = $params['register_time'];

                    $updateDataProject['register_time'] = strtotime($params['register_time']);
                    $updateDataProject['register_time_desc'] = $params['register_time'];
                }
                if(isset($params['land_time']))
                {
                    $updateData['land_time'] = strtotime($params['land_time']);
                    $updateData['land_time_desc'] = $params['land_time'];

                    $updateDataProject['land_time'] = strtotime($params['land_time']);
                    $updateDataProject['land_time_desc'] = $params['land_time'];
                }
                if(isset($params['start_construction_time']))
                {
                    $updateData['start_construction_time'] = strtotime($params['start_construction_time']);
                    $updateData['start_construction_time_desc'] = $params['start_construction_time'];

                    $updateDataProject['start_construction_time'] = strtotime($params['start_construction_time']);
                    $updateDataProject['start_construction_time_desc'] = $params['start_construction_time'];
                }

                if(isset($params['operate_time']))
                {
                    $updateData['operate_time'] = strtotime($params['operate_time']);
                    $updateData['operate_time_desc'] = $params['operate_time'];
                }

                if(isset($params['remove_time']))
                {
                    $updateData['remove_time'] = strtotime($params['remove_time']);
                    $updateData['remove_time_desc'] = $params['remove_time'];
                }

                if (isset($params['settle_street_ids'])) {
                    $row_info = $this->chargedep_model->get($params['settle_street_ids']);
                    $accompany_name = $row_info->name;
                    $updateData['settle_street_ids'] = $params['settle_street_ids'];
                    $updateData['settle_street_names'] = $accompany_name;
                }

                if (isset($params['chargedep_ids'])) {
                    $row_info = $this->chargedep_model->get($params['chargedep_ids']);
                    $accompany_name = $row_info->name;
                    $updateData['chargedep_ids'] = $params['chargedep_ids'];
                    $updateData['chargedep_names'] = $accompany_name;
                }

                if(isset($params['status_id'])) {
                    $row_info = $this->progress_model->get($params['status_id']);
                    $accompany_name = $row_info->name;
                    $updateData['status_id'] = $params['status_id'];
                    $updateData['status'] = $accompany_name;
                }

                $updateData['investment_total'] = $params['investment_total'];
                $updateData['carrier_area'] = $params['carrier_area'];
                $updateData['summary'] = $params['summary'];
                $updateData['status_name'] = $params['status_name'];
                $updateData['exist_question'] = $params['exist_question'];

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    // 更新command表 顺便更新project
                    $result = $row->allowField(true)->save($updateData);
                    if(isset($project_row))
                    {
                        $row_project = $this->projectmodel->get($project_row['id']);
                        $row_project->allowField(true)->save($updateDataProject);
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assignconfig('ids',$ids);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    public function importcommand($typeid = null) {
        if($this->request->isPost()){
            $file = $this->request->request('filepath');

            $baseField = [1=>'name',2=>'investment_total',3=>'carrier_area',4=>'summary',5=>'status_name',6=>'exist_question',7=>'sign_time_desc',8=>'invesment_agreement_time_desc',9=>'remove_time_desc',10=>'land_time_desc',11=>'start_construction_time_desc',12=>'operate_time_desc',13=>'status',14=>'chargedep_names',15=>'settle_street_names',16=>'next_steps',17=>'access_time_desc'];
            $insert = $this->baseImportRead($baseField,'',3,$file);

            $insert_new = [];
            $sort = 0;
            $update = [];
            foreach ($insert as $v)
            {
                // 项目名称
                if(!empty($v['name']))
                {
                    // 先判断是否存在，如果存在更新。否则新增
                    $command_type = '';
                    $info = $this->command_model->get($typeid);
                    if($info)
                        $command_type = $info['name'];

                    // 责任单位
                    $settle_street_ids = '';
                    if(!empty($v['settle_street_names'])){
                        $charge_info = $this->chargedep_model->where(['name'=>$v['settle_street_names']])->find();
                        if(!empty($charge_info))
                            $settle_street_ids = $charge_info['id'];
                    }

                    // 协办单位
                    $chargedep_ids = '';
                    if(!empty($v['chargedep_names'])){
                        $chargedep_info = $this->chargedep_model->where(['name'=>$v['chargedep_names']])->find();
                        if(!empty($chargedep_info))
                            $chargedep_ids = $chargedep_info['id'];
                    }
                    if(!empty($v['status']))
                    {
                        switch ($v['status']) {
                            case '前期接洽':
                                $status_id = 1;
                                break;
                            case '项目初评':
                                $status_id = 2;
                                break;
                            case '准入':
                                $status_id = 3;
                                break;
                            case '框架协议':
                                $status_id = 4;
                                break;
                            case '正式协议':
                                $status_id = 5;
                                break;
                            case '注册':
                                $status_id = 6;
                                break;
                            case '拿地':
                                $status_id = 7;
                                break;
                            case '开工':
                                $status_id = 8;
                                break;
                            default:
                                $status_id = 0;
                                break;
                        }
                    }

                    $row_command = $this->model->where(['name'=>$v['name'],'command_typeid'=>$typeid])->find();
                    if(isset($row_command)){
                        $update[$sort] = [
                            'id'        => $row_command['id'],
                            'name'      => $v['name'],
                            'investment_total'=>$v['investment_total'],
                            'carrier_area'=>$v['carrier_area'],
                            'summary'=>$v['summary'],
                            'status_name'=>$v['status_name'],
                            'exist_question'=>$v['exist_question'],
                            'sign_time' => $v['sign_time_desc']>0?strtotime($v['sign_time_desc']):"",
                            'sign_time_desc' => $v['sign_time_desc'],
                            'invesment_agreement_time' => $v['invesment_agreement_time_desc']>0?strtotime($v['invesment_agreement_time_desc']):"",
                            'invesment_agreement_time_desc'=>$v['invesment_agreement_time_desc'],
                            'remove_time' => $v['remove_time_desc']>0?strtotime($v['remove_time_desc']):"",
                            'remove_time_desc'=>$v['remove_time_desc'],
                            'land_time' => $v['land_time_desc']>0?strtotime($v['land_time_desc']):"",
                            'land_time_desc' => $v['land_time_desc'],
                            'start_construction_time' => $v['start_construction_time_desc']>0?strtotime($v['start_construction_time_desc']):"",
                            'start_construction_time_desc' => $v['start_construction_time_desc'],
                            'operate_time' => $v['operate_time_desc']>0?strtotime($v['operate_time_desc']):"",
                            'operate_time_desc'       => $v['operate_time_desc'],
                            'status_id' => $status_id,
                            'status'  => $v['status'],
                            'chargedep_ids' => $chargedep_ids,
                            'chargedep_names'       => $v['chargedep_names'],
                            'settle_street_ids' => $settle_street_ids,
                            'settle_street_names'   => $v['settle_street_names'],
                            'command_type'   => $command_type,
                            'command_typeid'   => $typeid,
                            'next_steps'=>$v['next_steps'],
                            'access_time' => $v['access_time_desc']>0?strtotime($v['access_time_desc']):"",
                            'access_time_desc'       => $v['access_time_desc'],
                        ];
                    }else{
                        $project_pno = '';
                        $project_row = $this->projectmodel->where(['name'=>$v['name']])->find();
                        if($project_row)
                            $project_pno = $project_row['pno'];

                        $insert_new[$sort] = [
                            'project_pno'=>$project_pno,
                            'name'      => $v['name'],
                            'investment_total'=>$v['investment_total'],
                            'carrier_area'=>$v['carrier_area'],
                            'summary'=>$v['summary'],
                            'status_name'=>$v['status_name'],
                            'exist_question'=>$v['exist_question'],
                            'sign_time' => $v['sign_time_desc']>0?strtotime($v['sign_time_desc']):"",
                            'sign_time_desc' => $v['sign_time_desc'],
                            'invesment_agreement_time' => $v['invesment_agreement_time_desc']>0?strtotime($v['invesment_agreement_time_desc']):"",
                            'invesment_agreement_time_desc'=>$v['invesment_agreement_time_desc'],
                            'remove_time' => $v['remove_time_desc']>0?strtotime($v['remove_time_desc']):"",
                            'remove_time_desc'=>$v['remove_time_desc'],
                            'land_time' => $v['land_time_desc']>0?strtotime($v['land_time_desc']):"",
                            'land_time_desc' => $v['land_time_desc'],
                            'start_construction_time' => $v['start_construction_time_desc']>0?strtotime($v['start_construction_time_desc']):"",
                            'start_construction_time_desc' => $v['start_construction_time_desc'],
                            'operate_time' => $v['operate_time_desc']>0?strtotime($v['operate_time_desc']):"",
                            'operate_time_desc'       => $v['operate_time_desc'],
                            'status_id' => $status_id,
                            'status'  => $v['status'],
                            'chargedep_ids' => $chargedep_ids,
                            'chargedep_names'       => $v['chargedep_names'],
                            'settle_street_ids' => $settle_street_ids,
                            'settle_street_names'   => $v['settle_street_names'],
                            'command_type'   => $command_type,
                            'command_typeid'   => $typeid,
                            'next_steps'=>$v['next_steps'],
                            'access_time' => $v['access_time_desc']>0?strtotime($v['access_time_desc']):"",
                            'access_time_desc'       => $v['access_time_desc'],
                        ];
                    }

                }
            }
            if(empty($insert_new)&&empty($update))
            {
                $this->error('导入失败');
            }else{
                if($insert_new)
                    $this->model->saveAll($insert_new);
                if($update)
                    $this->model->saveAll($update);
                $this->success();
                exit();
            }
            //
        }
        $expurl = '/template/command.xlsx';

        $this->assign('expurl', $expurl);
        return $this->view->fetch('import');
    }


    public function del($ids = null ){
        $ids = $ids ? $ids : $this->request->param("ids");
        $row = $this -> model -> find($ids);
        if(!$row)
            $this->error('记录不存在');
        $row->delete();
        $this->success();
    }
    
    /*
    验证名称是否存在
    */
    public function ajaxname()
    {
        if($this -> request -> isAjax()){
            $data = $this -> request -> post('c_name');
            if(!empty($data))
            {
                $row = $this->model->where(['name'=>trim($data)])->find();
                if(isset($row))
                    return $this -> success('获取成功');
            }

        }
    }

    protected function baseImportRead($baseField=[],$type,$startRow = 2,$file){
        set_time_limit(0);
        ini_set('memory_limit', '1280M');
        // $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }

        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }
        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }

            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行

            $hotelName = '';
            if($this -> auth -> obj_id){
                $hotelName = (\app\admin\model\Hotel::get($this -> auth->obj_id)) -> name;
            }

            for ($currentRow = $startRow; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                foreach ($baseField as $fieldKey => $fieldValue) {
                    $val = $currentSheet->getCellByColumnAndRow($fieldKey, $currentRow)->getValue();
                    $values[] = trim(is_object($val) ? $val->__toString() : ($val == null ? '' : trim($val)));
                }

                $temp = array_combine($baseField, $values);
                if($type){
                    $temp['hotel_id'] = $this -> auth -> obj_id;
                    $temp['hotel_name'] = $hotelName;
                    $temp['status'] = 2;
                    $temp['type'] = $type;
                }
                $insert[] = $temp;

            }

        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }

        //是否包含admin_id字段
        $has_admin_id = false;
        foreach ($fieldArr as $name => $key) {
            if ($key == 'admin_id') {
                $has_admin_id = true;
                break;
            }
        }
        if ($has_admin_id) {
            $auth = Auth::instance();
            foreach ($insert as &$val) {
                if (!isset($val['admin_id']) || empty($val['admin_id'])) {
                    $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
                }
            }
        }
        return $insert;
    }


}
